from pydantic import BaseModel, Field
from typing import Optional, Any, Generic, TypeVar
from datetime import datetime
from .enums import MessageType, StatusCode

T = TypeVar('T')

class ResponseMessage(BaseModel, Generic[T]):
    """通用响应消息模型"""
    type: MessageType = Field(..., description="消息类型")
    code: StatusCode = Field(..., description="状态码")
    msg: str = Field(..., description="详细消息")
    data: Optional[T] = Field(None, description="响应数据")
    timestamp: datetime = Field(default_factory=datetime.now, description="时间戳")
    request_id: Optional[str] = Field(None, description="请求ID")
    
    class Config:
        """配置类"""
        use_enum_values = True  # 使用枚举值而不是枚举对象
        arbitrary_types_allowed = True
        json_encoders = {
            datetime: lambda v: v.isoformat()  # datetime序列化为ISO格式
        }
        
    @classmethod
    def success(cls, data: Any = None, msg: str = "操作成功") -> "ResponseMessage":
        """快速创建成功响应"""
        return cls(
            type=MessageType.SUCCESS,
            code=StatusCode.SUCCESS,
            msg=msg,
            data=data
        )
        
    @classmethod
    def error(cls, msg: str, code: StatusCode = StatusCode.SERVER_ERROR) -> "ResponseMessage":
        """快速创建错误响应"""
        return cls(
            type=MessageType.ERROR,
            code=code,
            msg=msg
        )
        
    @classmethod
    def notify(cls, msg: str, data: Any = None) -> "ResponseMessage":
        """快速创建通知响应"""
        return cls(
            type=MessageType.NOTIFY,
            code=StatusCode.SUCCESS,
            msg=msg,
            data=data
        )
